package com.markhsiu.nio.leaderus.mutinio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ThreadLocalRandom;
public class NIOAcceptor extends Thread{
	private final ServerSocketChannel serverSocketChannel;
	private final MyNIORector[] reactors;
	private final int mod;

	public NIOAcceptor(int bindPort,MyNIORector[] reactors) throws IOException {
		this.reactors=reactors;
		if(reactors == null){
			throw new RuntimeException();
		}
		this.mod =  reactors.length;
		serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(true);
		InetSocketAddress address = new InetSocketAddress(bindPort);
		serverSocketChannel.socket().bind(address);
		System.out.println("started at " + address);
	}

	public void run() {
		for(MyNIORector rector: reactors){
			rector.start();
		}
		
		while (true) {
			try {
				SocketChannel socketChannel = serverSocketChannel.accept();
				System.out.println("Connection Accepted "+socketChannel.getRemoteAddress());
				int nextReator = ThreadLocalRandom.current().nextInt(0, mod);
				reactors[nextReator].registerNewClient(socketChannel);
				
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}